//
//  UserInfoView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/2.
//

enum PermissionAlertType {
    case camera
    case photoLibrary
}

import SwiftUI
import URLImage
import PhotosUI
import AliyunOSSiOS
import Combine
import ToastUI


struct UserInfoView: View {
    @EnvironmentObject var appState: AppState
    @StateObject var profile = profileViewModel()
    @State private var showToast = false

    @State private var selectedImage: UIImage?
    @State private var showActionSheet = false
    @State private var showImagePicker = false
    @State private var showPermissionAlert = false
    @State private var permissionAlertType: PermissionAlertType = .camera
    @State private var uploadUrl = ""

    
    @State private var sourceType: UIImagePickerController.SourceType = .photoLibrary
    
    
    var birthDay : String {
        if let b = profile.userinfo?.data.birthday {
            let array = b.components(separatedBy: "T")
            return array.first ?? ""
        }else {
            return ""
        }
    }
    

    var timestampString: String = TimestampHelper.currentMilliTimestamp()
    var dateString: String = TimestampHelper.timestampToStringDay()
    
    var body: some View {
        ScrollView(.vertical) {
            VStack {
                Spacer().frame(height: getNavigationBarTotalHeight()+32)
                HStack {
                    Spacer()
                    Button(action: {
                        showActionSheet = true
                    }) {
                        if let avatar = profile.userinfo?.data.avatar,
                           let fullURL = URL(string: "https://oss-cn-shenzhen.aliyuncs.com\(avatar)") {
                            //调试，实验加载选择的照片
//                            if let selectedImage = selectedImage {
//                                Image(uiImage: selectedImage)
//                                    .resizable()
//                                    .scaledToFill()
//                                    .frame(width: 90, height: 90)
//                                    .clipShape(Circle())
//                            }
                            URLImage(url:fullURL) { image in
                                image
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .frame(width: 90, height: 90)
                                    .clipShape(Circle())
                            }
                        } else {
                            if let selectedImage = selectedImage,profile.isuploadSuccess {
                                Image(uiImage: selectedImage)
                                    .resizable()
                                    .scaledToFill()
                                    .frame(width: 90, height: 90)
                                    .clipShape(Circle())
                            }else {
                                Image("21")
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .frame(width: 90, height: 90)
                                    .clipShape(Circle())
                            }
                        }
                    }
                    Spacer()
                }
                Spacer().frame(height: 14)
                HStack {
                    //点击更换头像
                    Button(action: {
                        // 按钮点击动作
                        showActionSheet = true
                        showToast = false
                    }) {
                        Image("carme")
                            .resizable()
                            .frame(width: 18, height: 18)
                    }
                    Button("点击更换头像") {
                        showActionSheet = true
                        showToast = false
                    }
                    .font(.system(size: 14))
                    .foregroundStyle(.white)
                }
                .onChange(of: selectedImage) {
                    newValue in
                    if let image = newValue {
                        OSSImageUploader.shared.uploadImage(image: image, bucketName: "kosspot-watch", objectKey: "watch-images/\(dateString)/\(timestampString)") { uploadRes, error in
                            if (error == nil) {
                                uploadUrl = uploadRes
                                showToast = false
                                print(uploadRes)
                                profile.uploadImageAvatar(avatarUrl: uploadUrl)
                            }else {
                                profile.upError = uploadRes
                                showToast = true
                            }
                        }
                    }
                }
                .actionSheet(isPresented: $showActionSheet) {
                    ActionSheet(
                        title: Text("选择图片来源"),
                        buttons: [
                            .default(Text("拍照")) {
                                checkCameraPermission()
                            },
                            .default(Text("从相册选择")) {
                                checkPhotoLibraryPermission()
                            },
                            .cancel(Text("取消")) {
                                showActionSheet = false
                            }
                        ]
                    )
                }
                .sheet(isPresented: $showImagePicker) {
                    ImagePickerView(sourceType: sourceType, selectedImage: $selectedImage)
                }
                .alert(isPresented: $showPermissionAlert) {
                    switch permissionAlertType {
                    case .camera:
                        Alert(
                            title: Text("相机权限被拒绝"),
                            message: Text("请在设置中允许访问相机以拍摄照片"),
                            primaryButton: .default(Text("设置")) {
                                openSettings()
                            },
                            secondaryButton: .cancel(Text("取消"))
                        )
                    case .photoLibrary:
                        Alert(
                            title: Text("相册权限被拒绝"),
                            message: Text("请在设置中允许访问相册以选择照片"),
                            primaryButton: .default(Text("设置")) {
                                openSettings()
                            },
                            secondaryButton: .cancel(Text("取消"))
                        )
                    }
                }
                
                Spacer().frame(height: 34)
                VStack {
                    HStack {
                        Text("昵称")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#CACACA"))
                        Spacer()
                        Text(profile.userinfo?.data.nickName ?? "")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#FFFFFF"))
                    }.padding(15)
                    
                    
                    HStack {
                        Text("电话")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#CACACA"))
                        Spacer()
                        Text(profile.userinfo?.data.phonenumber ?? "")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#FFFFFF"))
                    }.padding(15)
                    
                    HStack {
                        Text("性别")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#CACACA"))
                        Spacer()
                        Text(Int(profile.userinfo?.data.sex ?? "")==1 ? "男" : "女")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#FFFFFF"))
                        Image("xiangyou")
                            .frame(width: 16,height: 16)
                    }.padding(15)
                    
                    HStack {
                        Text("生日")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#CACACA"))
                        Spacer()
                        Text(birthDay)
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#FFFFFF"))
                        Image("xiangyou")
                            .frame(width: 16,height: 16)
                    }.padding(15)
                    
                    HStack {
                        Text("体重")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#CACACA"))
                        Spacer()
                        Text("\((profile.userinfo?.data.weight ?? 0),specifier: "%.2f")KG")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#FFFFFF"))
                        Image("xiangyou")
                            .frame(width: 16,height: 16)
                    }.padding(15)
                    
                    HStack {
                        Text("身高")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#CACACA"))
                        Spacer()
                        Text("\((profile.userinfo?.data.height ?? 0),specifier: "%.2f")CM")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#FFFFFF"))
                        Image("xiangyou")
                            .frame(width: 16,height: 16)
                    }.padding(15)
                    
                }
                .gradientBackground(colors: [Color(hex: "#1E1E1E")], cornerRadius: 16)
                .padding(.horizontal,12)
                
                Spacer().frame(height: 12)
                
                VStack {
                    
                    HStack {
                        Text("运动目标")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#CACACA"))
                        Spacer()
                        Text("\(profile.userinfo?.data.targetDistance ?? 0)")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#FFFFFF"))
                    }.padding(15)
                    
                    
                    HStack {
                        Text("运动状态")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#CACACA"))
                        Spacer()
                        Text("\(profile.userinfo?.data.targetSteps ?? 0)")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#FFFFFF"))
                    }.padding(15)
                    
                }.gradientBackground(colors: [Color(hex: "#1E1E1E")], cornerRadius: 16)
                    .padding(.horizontal,12)
                
                Spacer()
                HStack {
                    Button {
                        
                    } label: {
                        Text("修改")
                            .font(.system(size: 16))
                            .foregroundStyle(Color(hex: "#242424"))
                        
                    }
                }
                .frame(maxWidth: .infinity, alignment: .center)
                .frame(height: 44)
                .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")], type: .linear(start: .leading, end: .trailing), cornerRadius: 22.0)
                .padding(.horizontal,12)
                .padding(.bottom,20)
            }
            .frame(minHeight: UIScreen.main.bounds.height)
        }
        .toast(isPresented: $showToast) {
            ShowMessageView(message: profile.upError)
           /* ToastView(profile.upError ?? "")
                .foregroundColor(.white)
                .background(Color.clear)
                .cornerRadius(8)
                .blur(radius: 0)
                .edgesIgnoringSafeArea(.all) */
        }
        .onChange(of: profile.upError) {
            newValue in
            if let errorMessage = newValue, !errorMessage.isEmpty {
                showToast = true
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    showToast = false
                    profile.upError = nil
                }
            }
        }
        .background(Color(hex: "#0A0A0A"))
        .ignoresSafeArea()
        .customNavigationBar(title: "个人信息", backButtonAction: {
            appState.navigateBack()
        }, backgroundColor: UIColor(Color(hex: "#0A0A0A")))
        
    }
    
    
    private func checkCameraPermission() {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        permissionAlertType = .camera
        switch status {
        case .authorized:
            sourceType = .camera
            showImagePicker = true
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { granted in
                DispatchQueue.main.async {
                    if granted {
                        sourceType = .camera
                        showImagePicker = true
                    } else {
                        showPermissionAlert = true
                    }
                }
            }
        default:
            showPermissionAlert = true
        }
    }
    
    private func checkPhotoLibraryPermission() {
        let status = PHPhotoLibrary.authorizationStatus()
        permissionAlertType = .photoLibrary
        switch status {
        case .authorized:
            sourceType = .photoLibrary
            showImagePicker = true
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization { newStatus in
                DispatchQueue.main.async {
                    if newStatus == .authorized {
                        sourceType = .photoLibrary
                        showImagePicker = true
                    } else {
                        showPermissionAlert = true
                    }
                }
            }
        default:
            showPermissionAlert = true
        }
    }
    
    private func openSettings() {
        if let url = URL(string: UIApplication.openSettingsURLString) {
            UIApplication.shared.open(url)
        }
    }
}

#Preview {
    UserInfoView()
}

struct ImagePickerView: UIViewControllerRepresentable {
    var sourceType: UIImagePickerController.SourceType
    @Binding var selectedImage: UIImage?
    @Environment(\.presentationMode) private var presentationMode
    
    func makeUIViewController(context: Context) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.sourceType = sourceType
        picker.delegate = context.coordinator
        picker.allowsEditing = true
        return picker
    }
    
    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        var parent: ImagePickerView
        
        init(_ parent: ImagePickerView) {
            self.parent = parent
        }
        
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            if let image = info[.editedImage] as? UIImage ?? info[.originalImage] as? UIImage {
                parent.selectedImage = image
            }
            parent.presentationMode.wrappedValue.dismiss()
        }
    }
}
